package com.patui.Ui;
import android.app.Activity;
import android.graphics.Bitmap;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Bundle;
import android.webkit.SslErrorHandler;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.patui.DataStructure.MsgInfo;
import com.patui.Logic.AlllActivityName;
import com.patui.Logic.FrameSevice;
import com.patui.Weibo.AccessToken;
import com.patui.Weibo.Weibo;
import com.patui.Weibo.WeiboException;
public class LoginWebViewActivity extends Activity {
	private  WebView mWebView;
	//private final String TAG = "AuthorizationAct";
	
	@Override
    protected void onCreate(Bundle savedInstanceState) {
	    super.onCreate(savedInstanceState);
	    FrameSevice.addActivity(LoginWebViewActivity.this);
	    String url = getIntent().getStringExtra("loadUrl");
	    mWebView=new WebView(this);
	    mWebView.loadUrl(url);
		setContentView(mWebView);
		mWebView.clearCache(true);
		mWebView.getSettings().setJavaScriptEnabled(true);
		mWebView.getSettings().setSupportZoom(true);
		mWebView.getSettings().setBuiltInZoomControls(true);
		mWebView.setWebViewClient(new WebViewC()); 
		
    }
	
	class WebViewC extends WebViewClient{
		private int index = 0;
		@Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
			view.loadUrl(url);
			return true;
        }
		public void onReceivedSslError (WebView view, SslErrorHandler handler, SslError error) {
			 handler.proceed() ;
		 }

		@Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
	        super.onPageStarted(view, url, favicon);
	        if( url.contains(Weibo.callBackUrl) && index == 0){
	        	index ++;
	        	Uri uri = Uri.parse(url);
	        	String oauth_verifier = uri.getQueryParameter("oauth_verifier");
	        	Weibo mWeibo=Weibo.getInstance();
	        	mWeibo.SetOauthverifier(oauth_verifier);
	            try {
	        		AccessToken mAccessToken=mWeibo.generateAccessToken(getApplicationContext(), mWeibo.getRequestToken());
	        		mWeibo.setAccessToken(mAccessToken);
	        		FrameSevice.saveUserInfo(mAccessToken.getToken(), mAccessToken.getSecret(), mAccessToken.getmUserId());
	         		FrameSevice.addStartActivityTask(new MsgInfo(AlllActivityName.MainTabActivity, null));
	            	LoginWebViewActivity.this.finish();
				} catch (WeiboException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
	        	
           }
	       
        }

		@Override
        public void onPageFinished(WebView view, String url) {
	        // TODO Auto-generated method stub
	        super.onPageFinished(view, url);
        }
	}
}
